import { useState, useEffect, useReducer, useRef } from "react"
import { connect } from "dva"
import { Input, Button, Checkbox, Tag, message, Spin } from "antd"
import { EyeInvisibleOutlined, EyeTwoTone } from "@ant-design/icons"
import * as loginApi from "@/services/login"
import { to } from "@/utils/index"
import { history } from "umi"

import styles from "./index.less"

// 账号密码登录类型
interface PassLoginType {
  phone: string
  loginPwd: string
  hospitalUuid: string
  deviceType: number
}


const initFormVal = {
  phone: "",
  loginPwd: "",
  hospitalUuid: "b2514da7aed211eb9c92000c29ff61fb",
  deviceType: 1
}




interface ActionType {
  key: keyof PassLoginType
  val: any
}

const formReducer = (state: PassLoginType, action: ActionType) => ({ ...state, [action.key]: action.val })


function login(props: any) {
  // console.log("state:", props)

  const [htmlNum, sethtmlNum] = useState<number>(1) // 中间视图显示切换，1默认是密码登录，2是手机号，3是扫码
  const [formVal, dispatchForm] = useReducer(formReducer, initFormVal)
  const [loading, setLoading] = useState<boolean>(false)

  const timeNum = 10
  let timer = useRef()
  let [yztime, setYztime] = useState<number>(timeNum) // 倒计时
  let siv: any


  const checkboxChang = (e: any) => {
    console.log(`checked = ${e.target.checked}`)
  }

  // 默认密码登录
  const PassLogin = () => {
    const [phone, setPhone] = useState<string>("")
    const [loginPwd, setLoginPwd] = useState<string>("")

    let pam = {
      phone: phone,
      loginPwd: loginPwd,
      hospitalUuid: "b2514da7aed211eb9c92000c29ff61fb",
      deviceType: 1,
    }
    const html = <>
      {/* {  loading ? <Spin size="large" tip="请稍后..." /> : null} */}

      {/* <Input maxLength={11} value={passval} onChange={e => dispatchForm({ key: "phone", val: e.target.value })} className={styles.input} placeholder="请输入手机号" /> */}
      <Input maxLength={11} value={phone} onChange={e => setPhone(e.target.value)} className={styles.input} placeholder="请输入手机号" />
      <Input.Password className={styles.input} placeholder="请输入密码"
        maxLength={16}
        value={loginPwd}
        onChange={e => setLoginPwd(e.target.value)}
        iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
      />

      <div className={styles.threeWrap} >
        <div  > <Checkbox style={{ fontSize: "12px", color: "rgba(0, 0, 0, 0.45)" }} onChange={checkboxChang}>记住密码</Checkbox> </div>
        <div>忘记密码?</div>
      </div>

      <Button loading={loading} onClick={() => loginEvent(pam)} className={styles.loginBtn} type="primary" block>登录</Button>

      <div onClick={() => loginBtnChange(2)} className={styles.phoneBtn} >手机号登录</div>
    </>
    return html
  }

  // 手机号登录
  const PhoneLogin = () => {
    const html = <>
      <Input className={styles.input} placeholder="请输入手机号" />

      <div className={styles.threeWrap} >
        <Input style={{ marginBottom: 0 }} className={styles.input} placeholder="请输入验证码" />
        <Tag onClick={getYzm} className={styles.phoneTag} >
          {loading ? Number(yztime) + "秒后重发" : "获取验证码"}
        </Tag>
      </div>

      <Button className={styles.loginBtn} type="primary" block>登录</Button>

      <div onClick={() => loginBtnChange(1)} className={styles.phoneBtn} >账号密码登录</div>
    </>
    return html
  }

  // 顶部二维码
  const Ewm = () => {
    let htmlE: JSX.Element = <div />
    if (htmlNum === 3) {
      htmlE = <img onClick={() => loginBtnChange(1)} style={{ position: "absolute", right: "10px", cursor: "pointer" }} src={require("@/asstes/login/icon-dn.png")} />

    } else {
      htmlE = <img onClick={() => loginBtnChange(3)} style={{ position: "absolute", right: "10px", cursor: "pointer" }} src={require("@/asstes/login/ewm.png")} />
    }
    return htmlE
  }

  const ShowHtml = () => {
    if (htmlNum === 1) {
      return <PassLogin /> // PassLogin()
    } else if (htmlNum === 2) {
      return <PhoneLogin /> // PhoneLogin()
    } else if (htmlNum === 3) {
      return "此处显示二维码"
    }
  }

  // 1默认是密码登录，2是手机号，3是扫码
  const loginBtnChange = (num: number): void => {
    setLoading(false)
    sethtmlNum(num)
  }



  // 密码登录按钮
  const loginEvent = async (pam: PassLoginType) => {
    // console.log(formVal)
    console.log(pam)
    if (htmlNum === 1) {
      if (!pam.phone || pam.phone === "" || pam.phone.length < 11 || !(/^1[3456789]\d{9}$/.test(pam.phone))) {
        message.error("请输入正确的手机号")
        return
      } else if (!pam.loginPwd || pam.loginPwd === "") {
        message.error("密码不能为空")
        return
      }
      setLoading(true)
      const [err, res] = await loginApi.login(pam)

      if (err) {
        setLoading(false)
        return message.error(err.message)
      }

      props.dispatch({
        type: "index/updateUserInfo",
        payload: res?.data
      })
      setLoading(false)

      history.push({
        pathname: "/index",
        query: {

        },
      })


    } else if (htmlNum === 2) {
      //
    } else if (htmlNum === 3) {
      // return "此处显示二维码"
    }


  }

  // 倒计60s
  const count = () => {
    timer.current = setInterval(() => {
      // setYztime(yztime--)
      setYztime(yztime--)
      if (yztime <= -1) {
        clearInterval(timer.current)
        setLoading(false)
        setYztime(timeNum) // 起步
      }
    }, 1000)

  }

  // 获取验证码
  const getYzm = () => {
    clearInterval(timer.current)
    setYztime(timeNum)
    setLoading(true)

    count()
  }


  // 初始化
  useEffect(() => {
    // console.log('useEffect初始化');
  }, [])



  return (
    <div className={styles.loginWrap}>
      <div style={{ height: "100%" }} className="flex-c">
        <div className={styles.left}>
          <img src={require("@/asstes/login/login-bg.png")} />
        </div>
        <div className={styles.right}>
          <div className={styles.top}>
            <div className={styles.topDiv}>
              <img src={require("@/asstes/login/icon.png")} />
              <span className={styles.title}>多学科会诊</span>
            </div>
            <Ewm />
          </div>

          {ShowHtml()}


        </div>
      </div>
    </div>
  )
}

// 字面意思就是，把models的state变成组件的props
function mapStateToProps(state: any) {
  // const {num} = state.index // index就是models命名空间名字
  return state// state.index
}

// 仓库和组件连接
export default connect(mapStateToProps)(login)
